package me.maiz.babyisland.admin.config;

import com.google.common.eventbus.AsyncEventBus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;
import java.util.concurrent.*;

@Configuration
@Slf4j
public class GuavaEventBusConfig {

    @Bean(name = "asyncEventBus")
    public AsyncEventBus getAsyncEventBus() {
        ThreadPoolExecutor executor=new ThreadPoolExecutor(10,150,100,
                TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(100),
                new CustomThreadFactory(),
                new CustomRejectedExecutionHandler());
        return new AsyncEventBus(executor);
    }

    private class CustomThreadFactory implements ThreadFactory {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(UUID.randomUUID().toString());
            t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
            return t;
        }
    }

    private class CustomRejectedExecutionHandler implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            log.info("线程池缓冲队列超出范围抛弃");
        }
    }

    private class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            log.error("线程池异常捕获打印：", e);
        }
    }


}
